// ==UserScript==
// @name         upload_btn
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  help auto-feed support btn
// @author       tomorrow505
// @match        https://greasyfork.org/zh-CN/script_versions/new
// @icon         https://www.google.com/s2/favicons?domain=greasyfork.org
// @grant        none
// ==/UserScript==

if (GM_getValue('btn_info') !== undefined) {
    raw_info = JSON.parse(GM_getValue('btn_info'));
    raw_info = fill_raw_info(raw_info);
    if (raw_info.name.match(/S\d+ E\d+/)) {
        raw_info.name = raw_info.name.replace(/(S\d+) (E\d+)/, '$1$2');
    }
    var search_name = get_search_name(raw_info.name);
    if (raw_info.name.match(/complete/i) && !raw_info.name.match(/S\d+/i)) {
        raw_info.name = raw_info.name.replace(/complete/i, 'S01');
    } else if (raw_info.name.match(/complete/i) && raw_info.name.match(/S\d+/i)) {
        raw_info.name = raw_info.name.replace(/complete/i, '');
    }
    if ($('#post').parent().parent().parent().parent().css('display') != 'none') {
        try{
            var announce = $('input[value*="announce"]').val();
            addTorrent(raw_info.torrent_url, raw_info.torrent_name, 'BTN', announce);
            $('#file').on('change', function(){
                if ($('#show_info').length) {
                    $('#show_info').html('<font color="yellow">Self-Torrent Re-Loaded！！！！</font>')
                } else {
                    $(this).after(`<div id='show_info' style="display:inline-block; margin-left:5px"><font color="yellow">Torrent Loaded！！！！</font></div>`);
                }
            });
        } catch(err) {}
        $('#content').find('table').first().hide();
        $('td.label:contains(Release Name)').last().parent().before($(`<tr><td class="label">Links</td>
            <td><input type="text" id="imdbid" name="imdbid" size="60" />
            <input id="fill" type="button" value="辅助发布">
            </td></tr>`));
        if (raw_info.url) {
            $('#imdbid').val(raw_info.url);
        } else if (raw_info.tmdb_url !== undefined) {
            $('#imdbid').val(raw_info.tmdb_url);
        } else if (raw_info.tvdb_url !== undefined) {
            $('#imdbid').val(raw_info.tvdb_url);
        }
        $('#scenename').val(raw_info.name);
        $('#scenename').after(`<div id='remind_scenename' style="display:inline-block; margin-left:5px"><font color="red">请点击辅助发布后检查！！</font></div>`);
        if (!$('#tags').val()) {
            $('#tags').after(`<div id='remind_tags' style="display:inline-block; margin-left:5px"><font color="red">请选择对应的标签！！</font></div>`);
        }
        if (raw_info.descr.match(/\[quote\]/)){
            raw_info.descr = raw_info.descr.slice(raw_info.descr.match(/\[quote\]/).index);
        }
        try {
            var info = get_mediainfo_picture_from_descr(raw_info.descr);
            var mediainfo = info.mediainfo;//图片
        } catch (err) {
            mediainfo = '';
        }
        if (!mediainfo) {
            mediainfo = raw_info.descr.replace(/\[\/?(quote|code)\]/g, '').trim();
        }
        if (raw_info.full_mediainfo) {
            mediainfo = raw_info.full_mediainfo;
        }
        $('#release_desc').val(mediainfo.replace(/\[\/?(quote|code)\]/g, '').trim());
        if (!mediainfo.match(/Video[\s\S]{0,10}?ID/)) {
            $('#fill').after(`<div id='remind_desc'><font color='red'>请先将mediainfo补充完整后点击辅助发布！！</font></div>`)
        }
        setTimeout(function() {
            $('#fill').click(function(){
                $('#remind_scenename').find('font').css('color', 'yellow').text('已经点击辅助发布，请检查！！');
                var name = $('#scenename').val().trim();
                var title = $('#title').val().trim();
                if (title == name.replace(/ /g, '.')) {
                    if (name.match(/E\d+/i) && !name.match(/S\d+E\d+/i)) {
                        name = name.replace(/(E\d+)/, 'S01$1');
                        $('#title').val('S01' + title.match(/E\d+/)[0])
                    }
                }
                var tv_series = $('#artist').val();
                if (!tv_series.match(/(19|20)\d{2}/) && name.match(/(19|20)\d{2}[^pP]/)) {
                    name = name.replace(/(19|20)\d{2}/, ' ').replace(/ +/g, ' ');
                }
                if (tv_series.match(/(19|20)\d{2}/) && !name.match(/(19|20)\d{2}[^pP]/)) {
                    name = name.replace(search_name, tv_series.replace(/\(|\)/g, ' ') + ' ').replace(/ +/g, ' ');
                } else if (tv_series.match(/\(.*\)/)) {
                    var country = tv_series.match(/\((.*)\)/)[1];
                    if (!name.match(country)) {
                        name = name.replace(search_name, tv_series.replace(/\(|\)/g, ' ') + ' ').replace(/ +/g, ' ');
                    }
                } else {
                    name = name.replace(search_name, tv_series.replace(/\(|\)/g, ' ') + ' ').replace(/ +/g, ' ');
                }
                var tv_title = $('#title').val();
                if (name.match(/S\d+E\d+-E?\d+/)) {
                    name = name.replace(name.match(/S\d+E\d+-E?\d+/)[0], tv_title);
                } else if (name.match(/E\d+-E?\d+/)) {
                    name = name.replace(name.match(/E\d+-E?\d+/)[0], tv_title);
                } else if (!name.match(/S\d+/) && !tv_title.match(/Season/)) {
                    name = name.replace(search_name, `${search_name} ${tv_title} `).replace(/ +/g, ' ');
                } else if (!name.match(/S\d+/i) && tv_title.match(/Season/)) {
                    var season = tv_title.match(/\d+/)[0];
                    if (season.length < 2) {
                        name = name.replace(search_name, `${search_name} S0${season} `).replace(/ +/g, ' ');
                    } else {
                        name = name.replace(search_name, `${search_name} S${season} `).replace(/ +/g, ' ');
                    }
                } else if (name.match(/S\d+/) && !tv_title.match(/Season/)) {
                    name = name.replace(/S\d+(E\d+)?/, `${tv_title}`).replace(/ +/g, ' ');
                }
                name = name.replace(/4k/i, '2160p');
                function re_build_name(channels, name) {
                    var label = null;
                    var label_str = '';
                    if (channels == '1') {
                        label = /1\.0/;
                        label_str = '1.0';
                    } else if (channels == '2') {
                        label = /2\.0/;
                        label_str = '2.0';
                    } else if (channels == '6') {
                        label = /5\.1/;
                        label_str = '5.1';
                    } else if (channels == '8') {
                        label = /7\.1/;
                        label_str = '7.1';
                    }
                    if (!name.match(label)) {
                        name = name.replace(/(DDPA|AAC|DDP|FLAC|DTS|LPCM|TrueHD)/, `$1${label_str}`);
                    }
                    if (name.match(/(H.265|H.264)(.*?)(DDPA|AAC|DDP|FLAC|DTS|LPCM|TrueHD)(2\.0|1\.0|5\.1|7\.1)/)) {
                        name = name.replace(/(H.265|H.264)(.*?)(DDPA|AAC|DDP|FLAC|DTS|LPCM|TrueHD)(2\.0|1\.0|5\.1|7\.1)/, '$3 $4 $1 $2');
                    }
                    return name;
                }
                try{
                    var channels = (raw_info.descr + $('#release_desc').val()).match(/Channel.*?(\d)/)[1];
                    name = re_build_name(channels, name);
                } catch(err) {
                    if (raw_info.descr.match(/(AUDIO.*CODEC.*?|音频编码.*?)(2\.0|1\.0|5\.1|7\.1)/i)) {
                        channels = raw_info.descr.match(/(AUDIO.*CODEC.*?|音频编码.*?)(2\.0|1\.0|5\.1|7\.1)/i)[2];
                        if (!name.includes(channels)) {
                            name = name.replace(/(DDPA|AAC|DDP|FLAC|DTS|LPCM|TrueHD)/, `$1${channels}`);
                        }
                        if (name.match(/(H.265|H.264)(.*?)(DDPA|AAC|DDP|FLAC|DTS|LPCM|TrueHD)(2\.0|1\.0|5\.1|7\.1)/)) {
                            name = name.replace(/(H.265|H.264)(.*?)(DDPA|AAC|DDP|FLAC|DTS|LPCM|TrueHD)(2\.0|1\.0|5\.1|7\.1)/, '$3 $4 $1 $2');
                        }
                    } else if (raw_info.descr.match(/\d channels/i)) {
                        channels = raw_info.descr.match(/(\d) channels/i)[1];
                        name = re_build_name(channels, name);
                    }
                }
                if (name.match(/(WEB-DL|Bluray|HDTV).(1080p|4K|2160p|720p|480p)/i)) {
                    name = name.replace(/(WEB-DL|Bluray|HDTV).(1080p|4K|2160p|720p|480p)/i, '$2 $1');
                }
                name = name.replace(/'|’/g, '').replace(/ +/g, ' ').replace(' -', '-');
                $('#scenename').val(name.replace(/ /g, '.').replace(/(,|!|\?|'|;|\\|:)\./g, function(data){ return data[1] }));
                $('#origin').val('P2P');

                var info = $('#album_desc').val();
                if (!info.match(/Season/)) {
                    info = `[b]Episode Name: [/b]\n[b]Season: {s} [/b]\n[b]Episode: {e} [/b]\n[b]Aired: [/b]\n\n[b]Episode Overview: [/b]`;
                    try {
                        info = info.format({'s': parseInt(name.match(/S(\d+)/)[1])});
                        info = info.format({'e': parseInt(name.match(/E(\d+)/)[1])});
                        $('#album_desc').val(info);
                    } catch (err) {
                        console.log(err)
                    }
                }

                var codec = name.codec_sel();
                if (codec == 'H264' || codec == 'X264') {
                    $('#bitrate').val('H.264');
                } else if (codec == 'H265' || codec == 'X265') {
                    $('#bitrate').val('H.265');
                }
                var medium = name.medium_sel();
                if (medium == 'HDTV') {
                    $('#media').val('HDTV');
                } else if (medium == 'WEB-DL') {
                    $('#media').val('WEB-DL');
                } else if (medium == 'Blu-ray') {
                    $('#media').val('Bluray');
                }
                var standard = name.standard_sel();
                if (standard == '720p') {
                    $('#resolution').val('720p');
                } else if (standard == '1080p') {
                    $('#resolution').val('1080p');
                } else if (standard == '1080i') {
                    $('#resolution').val('1080i');
                } else if (standard == '4K') {
                    $('#resolution').val('2160p');
                }

                var mediainfo = $('#release_desc').val();
                if (mediainfo.match(/\.mp4/)) {
                    $('#format').val('MP4');
                } else if (mediainfo.match(/\.mkv/)) {
                    $('#format').val('MKV');
                } else if (mediainfo.match(/\.MPLS/)) {
                    $('#format').val('M2TS');
                }
                $('#international_box').attr('checked', true);
                var url = $('#imdbid').val();
                if (url.match(/tt\d+/)) {
                    var imdb_url = 'https://www.imdb.com/title/' + url.match(/tt\d+/)[0];
                    getDoc(imdb_url, null, function(doc) {
                        var country = Array.from($('li.ipc-metadata-list__item:contains("Countr")', doc).find('a')).map(function(e){
                            return $(e).text();
                        });
                        var country_selected = false;
                        country.map(function(e){
                            if (e == "UK") { e = 'United Kingdom'} else if (e == 'USA') { e = 'United States of America'}
                            if ($('#country').find(`option:contains(${e.trim()})`).length) {
                                if (!country_selected){
                                    country_selected = true;
                                    $('#country').find(`option:contains(${e.trim()})`).attr('selected', true);
                                    $('#country')[0].dispatchEvent(evt);
                                }
                            }
                        });
                        var language = $('li[data-testid="title-details-languages"]', doc).find('a').text().trim();
                        if (language == 'English') {
                            $('#international_box').attr('checked', false);
                        }
                    })
                } else if (url.match(/themoviedb/)) {
                    var tv_id = url.match(/tv\/(\d+)/)[1];
                    var search_url = `https://api.themoviedb.org/3/tv/${tv_id}?api_key=${used_tmdb_key}&language=en-US`;
                    getJson(search_url, null, function(data){
                        console.log(data)
                        var country = data.origin_country[0];
                        var country_dict = {
                            "AD": "Andorra",
                            "AF": "Afghanistan",
                            "AG": "Antigua Barbuda",
                            "AL": "Albania",
                            "AO": "Angola",
                            "AR": "Argentina",
                            "AT": "Austria",
                            "AU": "Australia",
                            "BB": "Barbados",
                            "BD": "Bangladesh",
                            "BE": "Belgium",
                            "BF": "Burkina Faso",
                            "BG": "Bulgaria",
                            "BN": "Brunei",
                            "BR": "Brazil",
                            "BS": "Bahamas",
                            "BZ": "Belize",
                            "CA": "Canada",
                            "CG": "Congo",
                            "CH": "Switzerland",
                            "CL": "Chile",
                            "CN": "China",
                            "CO": "Colombia",
                            "CR": "Costa Rica",
                            "CS": "Czech",
                            "CU": "Cuba",
                            "CY": "Cyprus",
                            "CZ": "Czech Republic ",
                            "DE": "Germany ",
                            "DK": "Denmark",
                            "DZ": "Algeria",
                            "EC": "Ecuador",
                            "EE": "Estonia",
                            "EG": "Egypt",
                            "ES": "Spain",
                            "FI": "Finland",
                            "FJ": "Fiji",
                            "FR": "France",
                            "GB": "United Kiongdom",
                            "GR": "Greece",
                            "GT": "Guatemala",
                            "HK": "Hongkong",
                            "HN": "Honduras",
                            "HU": "Hungary",
                            "ID": "Indonesia",
                            "IE": "Ireland",
                            "IL": "Israel",
                            "IN": "India",
                            "IR": "Iran",
                            "IS": "Iceland",
                            "IT": "Italy",
                            "JM": "Jamaica",
                            "JP": "Japan",
                            "KG": "Kyrgyzstan",
                            "KH": "Cambodia",
                            "KP": "North Korea",
                            "KR": "South Korea",
                            "KW": "Kuwait",
                            "LA": "Laos",
                            "LB": "Lebanon",
                            "LK": "Sri Lanka",
                            "LT": "Lithuania",
                            "LU": "Luxembourg",
                            "LV": "Latvia",
                            "MX": "Mexico",
                            "MY": "Malaysia",
                            "NG": "Nigeria",
                            "NL": "Netherlands",
                            "NO": "Norway",
                            "NR": "Nauru",
                            "NZ": "New Zealand",
                            "PE": "Peru",
                            "PH": "Philippines",
                            "PK": "Pakistan",
                            "PL": "Poland",
                            "PR": "Puerto Rico",
                            "PT": "Portugal",
                            "PY": "Paraguay",
                            "QA": "Qatar",
                            "RO": "Romania",
                            "RU": "Russia",
                            "SA": "Saudi Arabia",
                            "SC": "Seychelles",
                            "SE": "Sweden",
                            "SG": "Singapore",
                            "SI": "Slovenia",
                            "SK": "Slovakia",
                            "SN": "Senegal",
                            "TG": "Togo",
                            "TH": "Thailand",
                            "TM": "Turkmenistan ",
                            "TR": "Turkey",
                            "TT": "Trinidad and Tobago",
                            "TW": "Taiwan",
                            "UA": "Ukraine",
                            "US": "United States of America",
                            "UY": "Uruguay",
                            "UZ": "Uzbekistan",
                            "VE": "Venezuela",
                            "VN": "Vietnam",
                            "WS": "Western Samoa",
                            "YU": "Yugoslavia",
                            "ZA": "South Africa"
                        }
                        if (country_dict.hasOwnProperty(country)) {
                            country = country_dict[country];
                        }
                        if ($('#country').find(`option:contains(${country.trim()})`).length) {
                            $('#country').find(`option:contains(${country.trim()})`).attr('selected', true);
                            $('#country')[0].dispatchEvent(evt);
                        }
                        var language = data.original_language;
                        if (language == 'en') {
                            $('#international_box').attr('checked', false);
                        }
                    });
                } else if (url.match(/thetvdb/)) {
                    getDoc(url, null, function(doc){
                        var country = $('strong:contains(Original Country)', doc).next().text();
                        if ($('#country').find(`option:contains(${country.trim()})`).length) {
                            $('#country').find(`option:contains(${country.trim()})`).attr('selected', true);
                            $('#country')[0].dispatchEvent(evt);
                        }
                        var language = $('strong:contains(Original Language)', doc).next().text();
                        if (language == 'English') {
                            $('#international_box').attr('checked', false);
                        }
                    });
                } else {
                    alert('没有相关链接，请自行填写剧集国名。');
                }
            });
            $('#country').after(`<div id="common_country" style="display:inline-block;margin-left:5px">
                    <a class="s_country" href="#" id="China">China</a> | 
                    <a class="s_country" href="#" id="Hong Kong">Hong Kong</a> | 
                    <a class="s_country" href="#" id="South Korea">South Korea</a>
                    <div style="display:inline-block;margin-left:5px" id="country_selected"><font color="red">请选择剧集对应的国家！！</font></div>
                </div>`);
            $('a.s_country').click((e)=>{
                e.preventDefault();
                var country = e.target.id;
                $(`#country`).find(`option:contains(${country})`).attr('selected', true);
                $(`#country`)[0].dispatchEvent(evt);
                $('#country_selected').css('color', 'yellow').text('已经选择对应的国家！！');
            });
            $('#country').on('change', function(){
                if (this.value != '---') {
                    $('#country_selected').css('color', 'yellow').text('已经选择对应的国家！！');
                }
            });
        }, 500);
        var dropZone = $('#release_desc')[0];
        dropZone.addEventListener("dragenter", function (e) {
            e.preventDefault();
            e.stopPropagation();
        }, false);

        dropZone.addEventListener("dragover", function (e) {
            e.preventDefault();
            e.stopPropagation();
        }, false);

        dropZone.addEventListener("dragleave", function (e) {
            e.preventDefault();
            e.stopPropagation();
        }, false);

        dropZone.addEventListener("drop", function (e) {
            e.preventDefault();
            e.stopPropagation();
            // 处理拖拽文件的逻辑
            var df = e.dataTransfer;
            var dropFiles = []; // 拖拽的文件，会放到这里
            var dealFileCnt = 0; // 读取文件是个异步的过程，需要记录处理了多少个文件了
            var allFileLen = df.files.length; // 所有的文件的数量，给非Chrome浏览器使用的变量

            // 获得拖拽文件的回调函数
            function getDropFileCallBack (dropFiles) {
                console.log(dropFiles, dropFiles.length);
            }

            // 检测是否已经把所有的文件都遍历过了
            function checkDropFinish () {
                if ( dealFileCnt === allFileLen-1 ) {
                    getDropFileCallBack(dropFiles);
                }
                dealFileCnt++;
            }

            if(df.items !== undefined){
                // Chrome拖拽文件逻辑
                for(var i = 0; i < df.items.length; i++) {
                    var item = df.items[i];
                    if(item.kind === "file" && item.webkitGetAsEntry().isFile) {
                        var file = item.getAsFile();
                        dropFiles.push(file);
                        file.text().then(function(data){
                            $('#release_desc').val(data);
                            $('#release_desc')[0].dispatchEvent(evt);
                        });
                    }
                }
            } else {
                // 非Chrome拖拽文件逻辑
                for(var i = 0; i < allFileLen; i++) {
                    var dropFile = df.files[i];
                    if ( dropFile.type ) {
                        dropFiles.push(dropFile);
                        checkDropFinish();
                    } else {
                        try {
                            var fileReader = new FileReader();
                            fileReader.readAsDataURL(dropFile.slice(0, 3));
                            fileReader.addEventListener('load', function (e) {
                                console.log(e, 'load');
                                dropFiles.push(dropFile);
                                checkDropFinish();
                            }, false);
                            fileReader.addEventListener('error', function (e) {
                                console.log(e, 'error，不可以上传文件夹');
                                checkDropFinish();
                            }, false);
                        } catch (e) {
                            console.log(e, 'catch error，不可以上传文件夹');
                            checkDropFinish();
                        }
                    }
                }
            }
        }, false);

        $('#release_desc').on('change', function(){
            $('#remind_desc').find('font').css('color', 'yellow');
            if ($('#release_desc').val().match(/Video[\s\S]{0,10}?ID/)) {
                $('#remind_desc').find('font').text('Mediainfo已经补充，请检查后点击辅助发布！！')
            }
        });

        $('#album_desc').css({'width': '600px', 'height': '200px'});
        $('#release_desc').css({'width': '600px', 'height': '500px'});
    } else {
        function load_episodes(season_url) {
            if ($('#episode_jump').length) {
                $('#episode_jump').attr('href', season_url);
            } else {
                $('#tvdb_episode').after(`<a href="${season_url}" target="_blank" style="margin-left:3px" id="episode_jump">跳转</a>`);
            }
            getDoc(season_url, null, function(doc){
                if ($('table.table-bordered', doc).find('td').length > 3) {
                    $('#tvdb_episode').html('');
                    $('table.table-bordered', doc).find('td').map((index,e)=>{
                        if ($(e).text().match(/S\d+E\d+/)) {
                            $('#tvdb_episode').append(`<option val="${$(e).text().match(/S\d+(E\d+)/)[1]}">${$(e).text().match(/S\d+(E\d+)/)[1]}</option>`);
                        }
                    })
                }
            });
        }
        function add_info_bytvdb(tvdb_url) {
            raw_info.name = $('#autofill').val();
            if (raw_info.tvdb_url) {
                $('#tvdbid').val(raw_info.tvdb_url.match(/id=(\d+)/)[1]);
            }
            getDoc(tvdb_url, null, function(doc) {
                var tvdb_name = $('div[class="change_translation_text"][data-language="eng"]', doc).attr("data-title");
                if (tvdb_name) {
                    if (tvdb_name == '2 Days & 1 Night') {
                        tvdb_name = '1 Night 2 Days';
                    }
                    raw_info.name = raw_info.name.replace(/(19|20)\d{2}/, ' ');
                    raw_info.name = raw_info.name.replace(search_name.trim(), tvdb_name).replace(/ +/g, ' ');
                }
                var season = $('#tab-official', doc).find('a:last').text().trim();
                if (season.match(/\d{4}/)) {
                    raw_info.name = raw_info.name.replace(/S\d+/, `S${season.match(/\d{4}/)[0]}`);
                }
                $('#autofill').val(raw_info.name);
                $('.tvdb').attr('disabled', true).css("color", "grey");
                var container = $('#tvdb_season');
                $('#tab-official', doc).find('a').map((index,e)=>{
                    try{
                        container.prepend(`<option value="${$(e).text().match(/\d+/)[0]}" name="${$(e).attr('href')}">${$(e).text().trim()}</optipon>`);
                        container.find(`option:contains(${$(e).text().trim()})`).attr('selected', true);
                    } catch (err) {}
                });
                if ($('#tvdb_season').find(`option:selected`).val().match(/\d{4}/) && !raw_info.name.match(/\d{4}/)) {
                    $('#autofill').val($('#autofill').val().replace(/S\d+/, $('#tvdb_season').find(`option:selected`).val()));
                }
                load_episodes($('#tvdb_season').find(`option:selected`).attr('name'));
                container.on('change', function() {
                    if (this.value.length < 2) {
                        value = 'S0' + this.value;
                    } else {
                        value = 'S' + this.value;
                    }
                    load_episodes($(this).find(`option[value=${this.value}]`).attr('name'));
                    $('#autofill').val($('#autofill').val().replace(/S\d+/, value));
                });
            });
        }
        $('#content').find('table').first().hide();
        if (raw_info.name.match(/e\d+/i) || raw_info.small_descr.match(/第\d+.*?集/)) {
            $('#categories').val('Episode');
        } else {
            $('#categories').val('Season');
        }
        $('#scene_yesno').val('Yes');

        $('#autofill_scene_yes').css({'display': 'block'});
        var $table = $('#autofill_scene_yes').find('td:contains(Release Name)').last().parent().parent();
        $table.prepend(`<tr><td style="text-align:right">剧集名称填写说明:</td>
            <td><font color="red">剧名以<a href="https://thetvdb.com/search?query=${search_name}" target="_blank">TVDB(点击跳转搜索)</a>为准,
            可能出现含有年份和国别如:EVE (2022)<br>或Insider (KR)。剧名没有年份则点击<a id="hide_year" href="#">→去掉年份←</a>(一般是没有年份的)</font><br>
            <b>检索TVDB名称：</b><input type="button" value="Search-By-IMDB" id="gettvdb" class="tvdb" title="根据imdb搜索" /><br>
            <b>剧集TVDB编号：</b><input type="text" value="" id="tvdbid" class="tvdb" style="width:86px" />
            <input type="button" value="获取TVDB信息" style="margin-left:2px" id="gettvdb2" class="tvdb" /><br>
            <b>Season数选择：</b><select id="tvdb_season" style="width:94px; margin-left:2px"></select><select id="tvdb_episode" style="width:86px; margin-left:5px"></select>
            </td></tr>`);
        for (var i = 0; i <= 50; i++) {
            if ( i < 10 ) {
                $('#tvdb_episode').append(`<option value="E0${i}">E0${i}</option>`);
            } else {
                $('#tvdb_episode').append(`<option value="E${i}">E${i}</option>`);
            }
        }
        $('#tvdb_episode').on('change', function() {
            var name_k = $('#autofill').val();
            name_k = name_k.replace(/E\d+(-E?\d+)?/, this.value);
            if (name_k.match(/S\d+/) && !name_k.match(/E\d+/)) {
                name_k = name_k.replace(/(S\d+)/, `$1${this.value}`)
            }
            $('#autofill').val(name_k);
            $('#categories').val('Episode');
        });
        if (!raw_info.name.match(/S\d+/i)) {
            raw_info.name = raw_info.name.replace(search_name, `${search_name} S01 `).replace(/ +/g, ' ');
        }
        $('#autofill').val(raw_info.name);
        $('#hide_year').click((e)=>{
            e.preventDefault();
            var name = $('#autofill').val();
            name = name.replace(/(19|20)\d{2}/, ' ').replace(/ +/g, ' ');
            if (name.match(/S\d+ E\d+/)) {
                name = name.replace(/(S\d+) (E\d+)/, '$1$2');
            }
            $('#autofill').val(name);
        });
        if (!raw_info.url) {
            $('#gettvdb').attr('disabled', true).css("color", "grey");
        }
        $('#gettvdb').click((e)=>{
            var tmdb_url = `https://api.themoviedb.org/3/find/${raw_info.url.match(/tt\d+/)[0]}?api_key=${used_tmdb_key}&language=en-US&external_source=imdb_id`;
            console.log(tmdb_url)
            getJson(tmdb_url, null, function(data){
                console.log(data);
                var tv_id = '';
                if (data.tv_results.length) {
                    tv_id = data.tv_results[0].id;
                } else if (data.tv_season_results.length) {
                    tv_id = data.tv_season_results[0].id;
                } else if (data.tv_episode_results.length) {
                    tv_id = data.tv_episode_results[0].id;
                } else {
                    alert("暂无结果，请直接跳转搜索！！");
                }
                if (tv_id) {
                    var _url = `https://api.themoviedb.org/3/tv/${tv_id}/external_ids?api_key=${used_tmdb_key}`;
                    console.log(_url);
                    getJson(_url, null, function(d){
                        console.log(d)
                        if (d.tvdb_id) {
                            tvdb_id = d.tvdb_id;
                            $('#tvdbid').val(tvdb_id);
                            var tvdb_url = `https://www.thetvdb.com/?id=${tvdb_id}&tab=series`;
                            add_info_bytvdb(tvdb_url);
                            getDoc(tvdb_url, null, function(doc) {
                                var tvdb_name = $('div[class="change_translation_text"][data-language="eng"]', doc).attr("data-title");
                                if (tvdb_name) {
                                    raw_info.name = raw_info.name.replace(/(19|20)\d{2}/, ' ').replace(/ +/g, ' ');
                                    raw_info.name = raw_info.name.replace(search_name, `${tvdb_name} `).replace(/ +/g, ' ');
                                    if (raw_info.name.match(/S\d+ E\d+/)) {
                                        raw_info.name = raw_info.name.replace(/(S\d+) (E\d+)/, '$1$2');
                                    }
                                    var season = $('#tab-official', doc).find('a:last').text().trim();
                                    if (season.match(/\d{4}/)) {
                                        raw_info.name = raw_info.name.replace(/S\d+/, `S${season.match(/\d{4}/)[0]}`);
                                    }
                                    $('#autofill').val(raw_info.name);
                                    $('.tvdb').attr('disabled', true).css("color", "grey");
                                }
                            });
                        } else {
                            alert("暂无结果！！！");
                            $('.tvdb').attr('disabled', true).css("color", "grey");
                        }
                    });
                }
            });
        });
        $('#gettvdb2').click((e)=>{
            var tvdb_id = $('#tvdbid').val().match(/\d+/)[0];
            var tvdb_url = `https://www.thetvdb.com/?id=${tvdb_id}&tab=series`;
            add_info_bytvdb(tvdb_url);
        });
        if (raw_info.tvdb_url !== undefined) {
            add_info_bytvdb(raw_info.tvdb_url);
        }
    }
}